<!DOCTYPE html>
<html>
<head hexo-theme='https://volantis.js.org/#2.6.6'>
  <meta charset="utf-8">
  <!-- SEO相关 -->
  
    
  
  <!-- 渲染优化 -->
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <!-- 页面元数据 -->
  
    <title>R Basics - Jun&#39;s Blog</title>
  
    <meta name="keywords" content="R,Probability">
  
  
    <meta name="description" content="Vectors
To create a vector, use the c command, which stands for concatenate or combine.
1&gt; v &lt;- c(3,1,4,1,5,9)
To create a scalar, type
1&gt; n &lt...">
  

  <!-- feed -->
  
    <link rel="alternate" href="/junblog/atom.xml" title="Jun's Blog">
  

  <!-- import meta -->
  

  <!-- link -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13/css/all.min.css">
  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">

  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css">

  

  
  <link rel="shortcut icon" type='image/x-icon' href="https://cdn.jsdelivr.net/gh/xaoxuu/assets@master/favicon/favicon.ico">
  

  

  

  <!-- import link -->
  

  
  
    
<link rel="stylesheet" href="/junblog/css/style.css">

  

  <script>
    function setLoadingBarProgress(num) {
      document.getElementById('loading-bar').style.width=num+"%";
    }
  </script>

  
  
</head>

<body>
  
  <div id="loading-bar-wrapper">
  <div id="loading-bar"></div>
</div>
<header class="l_header shadow blur">
  <div class='container'>
  <div class='wrapper'>
    <div class='nav-sub'>
      <p class="title"></p>
      <ul class='switcher nav-list-h'>
        <li><a class="s-comment fas fa-comments fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
          <li><a class="s-toc fas fa-list fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
      </ul>
    </div>
		<div class="nav-main">
      
        
        <a class="title flat-box" target="_self" href='/junblog/'>
          
          
          
            Jun's Blog
          
          
        </a>
      

			<div class='menu navigation'>
				<ul class='nav-list-h'>
          
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/
                  
                  
                  
                    id="junblog"
                  >
                  <i class='fas fa-rss fa-fw'></i>首页
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/categories/
                  
                  
                  
                    id="junblogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/tags/
                  
                  
                  
                    id="junblogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/archives/
                  
                  
                  
                    id="junblogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/friends/
                  
                  
                  
                    id="junblogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/aboutme/
                  
                  
                  
                    id="junblogaboutme"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
              </li>
            
          
          
				</ul>
			</div>

      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <i class="icon fas fa-search fa-fw"></i>
          <input type="text" class="input u-search-input" placeholder="Search..." />
        </form>
      </div>

			<ul class='switcher nav-list-h'>
				
					<li><a class="s-search fas fa-search fa-fw" target="_self" href='javascript:void(0)'></a></li>
				
				<li>
          <a class="s-menu fas fa-bars fa-fw" target="_self" href='javascript:void(0)'></a>
          <ul class="menu-phone list-v navigation white-box">
            
              
            
              <li>
                <a class="flat-box" href=/junblog/
                  
                  
                  
                    id="junblog"
                  >
                  <i class='fas fa-rss fa-fw'></i>首页
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/categories/
                  
                  
                  
                    id="junblogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/tags/
                  
                  
                  
                    id="junblogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/archives/
                  
                  
                  
                    id="junblogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/friends/
                  
                  
                  
                    id="junblogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/aboutme/
                  
                  
                  
                    id="junblogaboutme"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
              </li>
            
          
            
          </ul>
        </li>
			</ul>
		</div>
	</div>
  </div>
</header>

<script>setLoadingBarProgress(40);</script>



  <div class="l_body nocover">
    <div class='body-wrapper'>
      

<div class='l_main'>
  

  
    <article id="post" class="post white-box reveal blur article-type-post" itemscope itemprop="blogPost">
      


  <section class='meta'>
    
      
      
      <div class="meta" id="header-meta">
        
          
  <h1 class="title">
    <a href="/junblog/2021/02/19/R%20Basics/">
      R Basics
    </a>
  </h1>


        
        <div class='new-meta-box'>
          
            
          
            
              
<div class='new-meta-item author'>
  <a href="" rel="nofollow">
    <img src="https://cdn.jsdelivr.net/gh/JunyuanHe/cdn-assets@master/img/GeographicObjects2.jpg">
    <p>Jun</p>
  </a>
</div>

            
          
            
              
  
  <div class='new-meta-item category'>
    <a href='/junblog/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA/R/' rel="nofollow">
      <i class="fas fa-folder-open fa-fw" aria-hidden="true"></i>
      <p>计算机/R</p>
    </a>
  </div>


            
          
            
              <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i>
    <p>发布于：2021年2月19日 15:15</p>
  </a>
</div>

            
          
            
              

            
          
        </div>
        
          <hr>
        
      </div>
    
  </section>


      <section class="article typo">
        <div class="article-entry" itemprop="articleBody">
          
          
          <h2 id="vectors">Vectors</h2>
<p>To create a vector, use the <code>c</code> command, which stands for <em>concatenate or combine</em>.</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; v &lt;- c(<span class="number">3</span>,<span class="number">1</span>,<span class="number">4</span>,<span class="number">1</span>,<span class="number">5</span>,<span class="number">9</span>)</span><br></pre></td></tr></table></figure>
<p>To create a scalar, type</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; n &lt;- <span class="number">100</span></span><br></pre></td></tr></table></figure>
<p>and R views n as a vector of length 1.</p>
<p>We can know many properties of a vector immediately. For instance, <code>sum(V)</code> adds up all the components of a vector and <code>max(v)</code> gives the largests element of v, <code>length(v)</code> returns the length of the vector v.</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; sum(v)</span><br><span class="line">[<span class="number">1</span>] <span class="number">23</span></span><br><span class="line">&gt; max(v)</span><br><span class="line">[<span class="number">1</span>] <span class="number">9</span></span><br><span class="line">&gt; min(v)</span><br><span class="line">[<span class="number">1</span>] <span class="number">1</span></span><br><span class="line">&gt; length(v)</span><br><span class="line">[<span class="number">1</span>] <span class="number">6</span></span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>Generating a subvector from an existing vector is easy</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; v[c(<span class="number">1</span>,<span class="number">3</span>,<span class="number">5</span>)]</span><br><span class="line">[<span class="number">1</span>] <span class="number">3</span> <span class="number">4</span> <span class="number">5</span></span><br><span class="line">&gt; v[-(<span class="number">2</span>:<span class="number">4</span>)]</span><br><span class="line">[<span class="number">1</span>] <span class="number">3</span> <span class="number">5</span> <span class="number">9</span></span><br></pre></td></tr></table></figure>
<p>Put the <code>c</code> command in the brackets, say<code>v[c(1,3,5)]</code> concatenates the 1st, 3rd and 5th element of the vector v and forms a new vector. <code>v[-(2:4)]</code> excludes the 2nd through 4th element from v.</p>
<blockquote>
<p>Notice in R the index is labelled from 1 rather than 0 !</p>
</blockquote>
<p>There's a shortcut for getting the vector (1,2, ... , n), see</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">v2 = <span class="number">1</span>:<span class="number">28</span></span><br></pre></td></tr></table></figure>
<p>Operations in R are performed component wise, e.g.</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>/(<span class="number">1</span>:<span class="number">20</span>)^<span class="number">5</span></span><br></pre></td></tr></table></figure>
<p>means <span class="math inline">\((1,1/2^5,1/3^5,\ldots,1/20^5)\)</span> .</p>
<p>If we add a shorter vector to a longer one, what will happen? see</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; v &lt;- c(<span class="number">3</span>,<span class="number">1</span>,<span class="number">4</span>,<span class="number">1</span>,<span class="number">5</span>,<span class="number">9</span>)</span><br><span class="line">&gt; v3 &lt;- c(<span class="number">100</span>, <span class="number">200</span>)</span><br><span class="line">&gt; v + v3</span><br><span class="line">[<span class="number">1</span>] <span class="number">103</span> <span class="number">201</span> <span class="number">104</span> <span class="number">201</span> <span class="number">105</span> <span class="number">209</span></span><br></pre></td></tr></table></figure>
<p>v3 is "recycled" and adds to v in a cycle.</p>
<h2 id="factorials-and-binomial-coefficients">Factorials and Binomial Coefficients</h2>
<p>We get <span class="math inline">\(n!\)</span> by <code>factorial(n)</code>, get <span class="math inline">\(\binom{n}{k}\)</span> by <code>choose(n,k)</code>.</p>
<p>What if <span class="math inline">\(n!\)</span> or <span class="math inline">\(\binom{n}{k}\)</span> get too large to compute? Fortunately, R gives functions to compute <span class="math inline">\(\log{n!}\)</span> or <span class="math inline">\(\log{\binom{n}{k}}\)</span> , by using <code>lfactorial(n)</code> and <code>lchoose(n,k)</code> respectively.</p>
<h2 id="r-for-probability---sampling-and-simulation">R for probability - Sampling and simulation</h2>
<p>The sample command generates random samples in R.</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; n &lt;- <span class="number">10</span>; k &lt;- <span class="number">5</span></span><br><span class="line">&gt; sample(n,k)</span><br></pre></td></tr></table></figure>
<p>generates a random sample of 5 from 1 to 10, without replacement and with equal probability assigned to each number.</p>
<p>We can also generate samples with replacement and give a probability to each number:</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; sample(<span class="number">4</span>, <span class="number">10</span>, replace = <span class="literal">TRUE</span>, prob = c(<span class="number">0.1</span>, <span class="number">0.2</span>, <span class="number">0.3</span>, <span class="number">0.4</span>))</span><br><span class="line"> [<span class="number">1</span>] <span class="number">3</span> <span class="number">4</span> <span class="number">4</span> <span class="number">4</span> <span class="number">3</span> <span class="number">2</span> <span class="number">4</span> <span class="number">3</span> <span class="number">3</span> <span class="number">2</span></span><br></pre></td></tr></table></figure>
<p>The above example draws 10 samples from {1, 2, 3, 4}, the probability of 1, 2, 3, 4 is respectively 0.1, 0.2, 0.3, 0.4</p>
<p>Use the <code>replicate</code> command generates many samples so that we can perform a simulation for a probability problem. Here is an example</p>
<blockquote>
<p><strong>Problem (matching problem)</strong> Consider a well-shuffled deck of n cards, labeled 1 through n. You flip over the cards one by one, saying the number 1 through n as you do so. You win the game if, at some point, the number you say aloud is the same as the number on the card being flipped over. What is the probability of winning?</p>
</blockquote>
<p><img src="/junblog/2021/02/19/R%20Basics/image-20210219150750127.png"></p>
<p><img src="/junblog/2021/02/19/R%20Basics/image-20210219150830674.png"></p>
<p>Simulation goes as follows</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; n &lt;- <span class="number">100</span></span><br><span class="line">&gt; r &lt;- replicate(<span class="number">10</span>^<span class="number">4</span>, sum(sample(n)==(<span class="number">1</span>:n)))</span><br><span class="line">&gt; sum(r&gt;=<span class="number">1</span>)/<span class="number">10</span>^<span class="number">4</span></span><br><span class="line">[<span class="number">1</span>] <span class="number">0.6344</span></span><br></pre></td></tr></table></figure>
<p>in which we generated <span class="math inline">\(10^4\)</span> examples and calculated the frequency of winning. The result agrees with mathematical derivation.</p>

          
            <div class='article_footer'>
              
                
  
    
    



  

  
    
    



  

  
    
    

    <section class="widget copyright  desktop mobile">
        <div class='content'>
            
                <blockquote>
                    
                        
                                    <p>博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议。转载请保留原文链接和作者。</p>

                                        
                                            
                </blockquote>
                
        </div>
    </section>
  

  


              
            </div>
          
        </div>
        
          


  <section class='meta' id="footer-meta">
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2021-02-19T15:21:45+08:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：2021年2月19日 15:21</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/junblog/tags/R/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>R</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/junblog/tags/Probability/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>Probability</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer"
          
          href="http://connect.qq.com/widget/shareqq/index.html?url=https://heliumhe.gitee.io/2021/02/19/R%20Basics/&title=R Basics - Jun's Blog&summary=Vectors
To create a vector, use the c command, which stands for concatenate or combine.
1&gt; v &lt;- c(3,1,4,1,5,9)
To create a scalar, type
1&gt; n &lt;- 100
and R views n as a vector of length 1.
We can know many properties of a vector immediately. For instance, sum(V) adds up all the components of a vector and max(v) gives the largests element of v, length(v) returns the length of the vector v.
12345678&gt; sum(v)[1] 23&gt; max(v)[1] 9&gt; min(v)[1] 1&gt; length(v)[1] 6"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/qq.png">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer"
          
          href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://heliumhe.gitee.io/2021/02/19/R%20Basics/&title=R Basics - Jun's Blog&summary=Vectors
To create a vector, use the c command, which stands for concatenate or combine.
1&gt; v &lt;- c(3,1,4,1,5,9)
To create a scalar, type
1&gt; n &lt;- 100
and R views n as a vector of length 1.
We can know many properties of a vector immediately. For instance, sum(V) adds up all the components of a vector and max(v) gives the largests element of v, length(v) returns the length of the vector v.
12345678&gt; sum(v)[1] 23&gt; max(v)[1] 9&gt; min(v)[1] 1&gt; length(v)[1] 6"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/qzone.png">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer"
          
          href="http://service.weibo.com/share/share.php?url=https://heliumhe.gitee.io/2021/02/19/R%20Basics/&title=R Basics - Jun's Blog&summary=Vectors
To create a vector, use the c command, which stands for concatenate or combine.
1&gt; v &lt;- c(3,1,4,1,5,9)
To create a scalar, type
1&gt; n &lt;- 100
and R views n as a vector of length 1.
We can know many properties of a vector immediately. For instance, sum(V) adds up all the components of a vector and max(v) gives the largests element of v, length(v) returns the length of the vector v.
12345678&gt; sum(v)[1] 23&gt; max(v)[1] 9&gt; min(v)[1] 1&gt; length(v)[1] 6"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/weibo.png">
          
        </a>
      
    
      
        
        <div class='hoverbox'>
          <a><img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/wechat.png"></a>
          <div class='target'>
            <img src="">
          </div>
        </div>
      
    
  </div>
</div>



        
      
    </div>
  </section>


        
        
          <div class="prev-next">
            
              <a class='prev' href='/junblog/2021/03/03/%E5%BC%80%E9%9B%86%E6%9E%84%E9%80%A0%E5%AE%9A%E7%90%86/'>
                <p class='title'><i class="fas fa-chevron-left" aria-hidden="true"></i>开集构造定理</p>
                <p class='content'>今日概率论课程, 使用了此定理. 即\(\mathbb{R}\)中的非空开集是可数个互不相交的开区间的并, 下面我们给出证明.


</p>
              </a>
            
            
              <a class='next' href='/junblog/2021/02/11/B002%20Classification%20-%20SGD/'>
                <p class='title'>B002 Classification - SGD Method<i class="fas fa-chevron-right" aria-hidden="true"></i></p>
                <p class='content'>What is a classification problem?
Imagine an elementary school student is given a batch of learn...</p>
              </a>
            
          </div>
        
      </section>
    </article>
  

  
    <!-- 显示推荐文章和评论 -->



  <article class="post white-box reveal comments blur">
    <section class="article typo">
      <p ct><i class='fas fa-comments'></i> 评论</p>
      
        <p cst>读者们可以在此处进行交流</p>
      
      
      
      
      
      
        <section id="comments">
          <div id="valine_container" class="valine_thread">
            <i class="fas fa-cog fa-spin fa-fw fa-2x"></i>
          </div>
        </section>
      
      
    </section>
  </article>


  




<!-- 根据页面mathjax变量决定是否加载MathJax数学公式js -->

  <script>
  // https://github.com/theme-next/hexo-theme-next/blob/master/layout/_third-party/math/mathjax.swig
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      loader: {
        source: {
          '[tex]/amsCd': '[tex]/amscd',
          '[tex]/AMScd': '[tex]/amscd'
        }
      },
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              let target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    (function () {
      var script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3.0/es5/tex-mml-chtml.js';
      script.defer = true;
      document.head.appendChild(script);
    })();
  } else {
    // 文章章节标题不能为 “MathJax” ，否则会报错。
    MathJax.startup.document.state(0);
    MathJax.texReset();
    MathJax.typeset();
  }
</script>




  <script>
    window.subData = {
      title: 'R Basics',
      tools: true
    }
  </script>


</div>
<aside class='l_side'>
  
  
    
    



  <section class="widget toc-wrapper blur desktop mobile" id="toc-div" >
    
  <header>
    
      <i class="fas fa-list fa-fw" aria-hidden="true"></i><span class='name'>本文目录</span>
    
  </header>


    <div class='content'>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#vectors"><span class="toc-number">1.</span> <span class="toc-text">Vectors</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#factorials-and-binomial-coefficients"><span class="toc-number">2.</span> <span class="toc-text">Factorials and Binomial Coefficients</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#r-for-probability---sampling-and-simulation"><span class="toc-number">3.</span> <span class="toc-text">R for probability - Sampling and simulation</span></a></li></ol>
    </div>
  </section>


  


</aside>


  
  <footer class="clearfix">
    <br><br>
    
      
        <div class="aplayer-container">
          


        </div>
      
    
      
        <br>
        <div class="social-wrapper">
          
            
              <a href="/junblog/atom.xml"
                class="social fas fa-rss flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
              </a>
            
          
            
              <a href="mailto:hejunyuan02@126.com"
                class="social fas fa-envelope flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
              </a>
            
          
            
              <a href="https://music.163.com/#/user/home?id=63035382"
                class="social fas fa-headphones-alt flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
              </a>
            
          
        </div>
      
    
      
        本站使用
        <a href="https://volantis.js.org/" target="_blank" class="codename">Volantis</a>
        作为主题，总访问量为
          <span id="busuanzi_value_site_pv"><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
          次
        
      
    
      
        <div class='copyright'>
        <p><a href="https://junyuanhe.github.io/" target="_blank" rel="noopener">Copyright © 2019-2020 Jun</a></p>

        </div>
      
    
  </footer>

<script>setLoadingBarProgress(80);</script>


      <script>setLoadingBarProgress(60);</script>
    </div>
    <a class="s-top fas fa-arrow-up fa-fw" href='javascript:void(0)'></a>
  </div>
  
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4/dist/jquery.min.js"></script>


  <script>
    
    var SEARCH_SERVICE = "hexo" || "hexo";
    var ROOT = "/junblog/" || "/";
    if (!ROOT.endsWith('/')) ROOT += '/';
  </script>





  <script async src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-volantis@2/js/instant_page.js" type="module" defer integrity="sha384-OeDn4XE77tdHo8pGtE1apMPmAipjoxUQ++eeJa6EtJCfHlvijigWiJpD7VDPWXV1"></script>


  <script src="https://cdn.jsdelivr.net/npm/scrollreveal@4.0.6/dist/scrollreveal.min.js"></script>
  <script type="text/javascript">
    $(function() {
      ScrollReveal().reveal('.l_main .reveal', {
        distance: '8px',
        duration: '800',
        interval: '100',
        scale: '1'
      });
    });
  </script>


  
<script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script>

  <script type="text/javascript">
    $(function() {
      Waves.attach('.flat-btn', ['waves-button']);
      Waves.attach('.float-btn', ['waves-button', 'waves-float']);
      Waves.attach('.float-btn-light', ['waves-button', 'waves-float', 'waves-light']);
      Waves.attach('.flat-box', ['waves-block']);
      Waves.attach('.float-box', ['waves-block', 'waves-float']);
      Waves.attach('.waves-image');
      Waves.init();
    });
  </script>


  <script defer src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-busuanzi@2.3/js/busuanzi.pure.mini.js"></script>



  
  
  
    
<script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script>

    <script type="text/javascript">
      $(function(){
        var imgs=["https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/41F215B9-261F-48B4-80B5-4E86E165259E.jpeg", "https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/BBC19066-E176-47C2-9D22-48C81EE5DF6B.jpeg", "https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/B18FCBB3-67FD-48CC-B4F3-457BA145F17A.jpeg", "https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/67239FBB-E15D-4F4F-8EE8-0F1C9F3C4E7C.jpeg"];
        if ('true' == 'true') {
          function shuffle(arr){
            /*From countercurrent-time*/
            var n = arr.length;
            while(n--) {
              var index = Math.floor(Math.random() * n);
              var temp = arr[index];
              arr[index] = arr[n];
              arr[n] = temp;
            }
          }
          shuffle(imgs);
        }
        if ('.cover') {
          $('.cover').backstretch(
            imgs,
          {
            duration: "20000",
            fade: "1500"
          });
        } else {
          $.backstretch(
            imgs,
          {
            duration: "20000",
            fade: "1500"
          });
        }
      });
    </script>
  











  
    
<script src="/junblog/js/valine.js"></script>

  
  <script>
  var GUEST_INFO = ['nick','mail','link'];
  var meta = 'nick,mail'.split(',').filter(function(item){
    return GUEST_INFO.indexOf(item) > -1
  });
  var REQUIRED_FIELDS = ['nick','mail','link'];
  var requiredFields = 'nick,mail'.split(',').filter(function(item){
    return REQUIRED_FIELDS.indexOf(item) > -1
  });
  var valine = new Valine();
  function emoji(path, idx, ext) {
      return path + "/" + path + "-" + idx + "." + ext;
  }
  var emojiMaps = {};
  for (var i = 1; i <= 54; i++) {
    emojiMaps['tieba-' + i] = emoji('tieba', i, 'png');
  }
  for (var i = 1; i <= 101; i++) {
    emojiMaps['qq-' + i] = emoji('qq', i, 'gif');
  }
  for (var i = 1; i <= 116; i++) {
    emojiMaps['aru-' + i] = emoji('aru', i, 'gif');
  }
  for (var i = 1; i <= 125; i++) {
    emojiMaps['twemoji-' + i] = emoji('twemoji', i, 'png');
  }
  for (var i = 1; i <= 4; i++) {
    emojiMaps['weibo-' + i] = emoji('weibo', i, 'png');
  }
  valine.init({
    el: '#valine_container',
    meta: meta,
    
    appId: "GbPm6UIzHrGduLaANgBIdhkf-gzGzoHsz",
    appKey: "SFuacIL4IJSnGk9TDX46eb0Y",
    placeholder: "快来评论吧~",
    pageSize:'10',
    avatar:'robohash',
    lang:'zh-cn',
    visitor: 'true',
    highlight: 'true',
    mathJax: 'true',
    enableQQ: 'true',
    requiredFields: requiredFields,
    emojiCDN: 'https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/emoji/valine/',
    emojiMaps: emojiMaps
  })
  </script>





  
<script src="/junblog/js/app.js"></script>



  
<script src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-volantis@2.6.5/js/search.js"></script>







<!-- 复制 -->

  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="fas fa-copy"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('fa-copy');
        $icon.addClass('fa-check-circle');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('fa-check-circle');
          $icon.addClass('fa-copy');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('fa-copy');
        $icon.addClass('fa-times-circle');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('fa-times-circle');
          $icon.addClass('fa-copy');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>




<!-- fancybox -->
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
<script>
  function pjax_fancybox() {
    $(".article-entry").find("img").not('.inline').not('a img').each(function () { //渲染 fancybox
      var element = document.createElement("a"); // a 标签
      $(element).attr("pjax-fancybox", "");  // 过滤 pjax
      $(element).attr("href", $(this).attr("src"));
      if ($(this).attr("data-original")) {
        $(element).attr("href", $(this).attr("data-original"));
      }
      $(element).attr("data-fancybox", "images");
      var caption = "";   // 描述信息
      if ($(this).attr('alt')) {  // 标准 markdown 描述信息
        $(element).attr('data-caption', $(this).attr('alt'));
        caption = $(this).attr('alt');
      }
      var div = document.createElement("div");
      $(div).addClass("fancybox");
      $(this).wrap(div); // 最外层套 div ，其实主要作用还是 class 样式
      var span = document.createElement("span");
      $(span).addClass("image-caption");
      $(span).text(caption); // 加描述
      $(this).after(span);  // 再套一层描述
      $(this).wrap(element);  // 最后套 a 标签
    })
    $(".article-entry").find("img").fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
      closeClick: true,
      helpers: {
        overlay: {closeClick: true}
      },
      buttons: [
        "zoom",
        "close"
      ]
    });
  };
  $(function () {
    pjax_fancybox();
  });
</script>





  <script>setLoadingBarProgress(100);</script>
</body>
</html>
